#include "log/log.h"
#include "app_message.h"
#include "cJSON/cJSON.h"
#include <string.h>
#include <stdlib.h>

/**
 * 将字符数组格式的消息数据转换为json格式的消息数据
    消息数据包含
        连接类型：1 代表蓝牙连接
        设备id: "xx"
        消息体内容: "abcd"
    字符数组格式： 1 2 4 xxabcd
        字节1：连接类型
        字节2：设备id长度
        字节3：消息体长度
        字节4~n：设备id和消息体
    json格式: {"conn_type": 1, "id": "5858", "msg": "61626364"}

 */

char *app_message_charsToJson(char *chars, int chars_len)
{
    // 从chars中提取出连接类型id长度和消息体长度
    int conn_type = chars[0];
    int id_len = chars[1];
    int msg_len = chars[2];
    if (chars_len != 3 + id_len + msg_len)
    {
        log_error("data lenth error");
        return NULL;
    }

    char id_chars[id_len];
    char msg_chars[msg_len];
    memcpy(id_chars, &chars[3], id_len);
    memcpy(msg_chars, &chars[3 + id_len], msg_len);

    // 将id和msg转换成16进制字符串
    char *id_hex = app_common_charsToHexstr(id_chars, id_len);
    char *msg_hex = app_common_charsToHexstr(msg_chars, msg_len);

    // 生成json格式的消息数据
    cJSON *cjson_obj = cJSON_CreateObject();

    cJSON_AddNumberToObject(cjson_obj, "conn_type", conn_type);
    cJSON_AddStringToObject(cjson_obj, "id", id_hex);
    cJSON_AddStringToObject(cjson_obj, "msg", msg_hex);

    char *json = cJSON_PrintUnformatted(cjson_obj);

    // 释放内存
    cJSON_Delete(cjson_obj);
    free(id_hex);
    free(msg_hex);
    return json;
}

//    json格式: {"conn_type": 1, "id": "5858", "msg": "61626364"}       字符数组格式： 1 2 4 xxabcd
int app_message_jsonToChars(char *json, char *chars_buf, int buf_len)
{
    // 解析json格式的消息数据
    cJSON *json_obj = cJSON_Parse(json);

    int conn_type = cJSON_GetObjectItem(json_obj, "conn_type")->valueint;
    char *id_hex = cJSON_GetObjectItem(json_obj, "id")->valuestring;
    char *msg_hex = cJSON_GetObjectItem(json_obj, "msg")->valuestring;
    int id_len = -1;
    char *id_chars = app_common_hexstrToChars(id_hex, &id_len);
    int msg_len = -1;
    char *msg_chars = app_common_hexstrToChars(msg_hex, &msg_len);

    int len = 3 + id_len + msg_len;
    if (len > buf_len)
    {
        cJSON_Delete(json_obj);
        log_error("buf_len is too small");
        return -1;
    }
    chars_buf[0] = conn_type;
    chars_buf[1] = id_len;
    chars_buf[2] = msg_len;
    memcpy(&chars_buf[3], id_chars, id_len);
    memcpy(&chars_buf[3 + id_len], msg_chars, msg_len);

    cJSON_Delete(json_obj);
    free(id_chars);
    free(msg_chars);
    return len;
}
